<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="name" label="传承人姓名" required label-width="100">
        <uni-easyinput placeholder="传承人姓名" v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="phone" label="联系电话" required label-width="100">
        <uni-easyinput placeholder="联系电话" v-model="formData.phone"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="email" label="电子邮箱" required label-width="100">
        <uni-easyinput placeholder="电子邮箱" v-model="formData.email" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="title" label="职业头衔" required label-width="100">
        <uni-easyinput placeholder="职业头衔" v-model="formData.title"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="direction" label="主要传承方向" required label-width="100">
        <uni-easyinput placeholder="主要传承方向" v-model="formData.direction"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="自我介绍" required label-width="100">
        <uni-easyinput placeholder="自我介绍" v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="level" label="传承人级别" required label-width="100">
        <uni-data-checkbox v-model="formData.level" :localdata="formOptions.level_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="avator_image" label="非遗传人头像" label-width="100">
        <button @click="chooseAvatorImage" size="mini">选择图片</button>
        <progress :percent="percentAvator" show-info stroke-width="3" />
        <image v-if="formData.avator_image" :src="formData.avator_image" style="width: 100px; height: 100px;"></image>
      </uni-forms-item>
      <uni-forms-item name="certificate_image" label="证明材料图片" label-width="100">
        <button @click="chooseCertificateImage" size="mini">选择图片</button>
        <progress :percent="percentCert" show-info stroke-width="3" />
        <image v-if="formData.certificate_image" :src="formData.certificate_image" style="width: 100px; height: 100px;"></image>
      </uni-forms-item>
      <uni-forms-item name="user_id" label="申请用户ID" label-width="100">
        <uni-easyinput placeholder="申请用户ID" v-model="formData.user_id" disabled></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="apply_date" label="申请时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.apply_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="audit_status" label="审核状态">
        <picker @change="pickerChange($event, 'audit_status')" :range="formOptions.audit_status_data" :value="formOptions.audit_status_index">
          <view>{{formOptions.audit_status_data[formOptions.audit_status_index] || "请选择..."}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="reject_reason" label="拒绝原因">
        <uni-easyinput placeholder="拒绝原因，仅在status为2时有值" v-model="formData.reject_reason" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="audit_time" label="审核时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.audit_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="auditor_id" label="审核人ID">
        <uni-easyinput placeholder="审核人ID" v-model="formData.auditor_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="honors" label="荣誉奖项">
        <uni-data-checkbox :multiple="true" v-model="formData.honors"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="portfolio" label="作品集">
        <uni-data-checkbox :multiple="true" v-model="formData.portfolio"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/intangible_master.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'intangible_master';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  export default {
    data() {
      let formData = {
        "user_id": "",
        "name": "",
        "avator_image": "",
        "phone": "",
        "email": "",
        "title": "",
        "direction": "",
        "description": "",
        "level": null,
        "certificate_image": "",
        "apply_date": null,
        "audit_status": 0,
        "reject_reason": "",
        "audit_time": null,
        "auditor_id": "",
        "honors": [],
        "portfolio": []
      }
      return {
        formData,
        percentAvator: 0,
        percentCert: 0,
        formOptions: {
          "level_localdata": [
            {
              "text": "国家级",
              "value": 1
            },
            {
              "text": "省级",
              "value": 2
            },
            {
              "text": "市级",
              "value": 3
            },
            {
              "text": "县级",
              "value": 4
            },
            {
              "text": "其他",
              "value": 5
            }
          ],
          "audit_status_data": numberRange(0, 2),
          "audit_status_index": null
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      pickerChange(e, name) {
        this.formOptions[name + '_index'] = e.detail.value;
        this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
        this.binddata(name, this.formData[name]);
      },
      chooseAvatorImage() {
        const _self = this;
        uniCloud.chooseAndUploadFile({
          type: 'image',
          count: 1,
          onChooseFile(res) {
            return Promise.all(res.tempFiles).then((fileList) => {
              let result = { tempFilePaths: [] };
              result.tempFiles = fileList.map((fileItem, index) => {
                result.tempFilePaths.push(fileItem.path);
                return {
                  path: fileItem.path,
                  cloudPath: '' + Date.now() + index + '.' + fileItem.name.split('.')[1],
                  fileType: fileItem.fileType
                }
              });
              return result;
            });
          },
          onUploadProgress(progressEvent) {
            _self.percentAvator = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          },
          success: async function(res) {
            let temp = await uniCloud.getTempFileURL({
              fileList: res.tempFiles.map((item) => item.url)
            });
            _self.formData.avator_image = temp.fileList[0].tempFileURL;
            uni.showToast({ icon: 'none', title: '上传成功', duration: 1500 });
          },
          fail: function(err) {
            uni.showToast({ icon: 'none', title: '上传失败', duration: 1500 });
          }
        });
      },
      chooseCertificateImage() {
        const _self = this;
        uniCloud.chooseAndUploadFile({
          type: 'image',
          count: 1,
          onChooseFile(res) {
            return Promise.all(res.tempFiles).then((fileList) => {
              let result = { tempFilePaths: [] };
              result.tempFiles = fileList.map((fileItem, index) => {
                result.tempFilePaths.push(fileItem.path);
                return {
                  path: fileItem.path,
                  cloudPath: '' + Date.now() + index + '.' + fileItem.name.split('.')[1],
                  fileType: fileItem.fileType
                }
              });
              return result;
            });
          },
          onUploadProgress(progressEvent) {
            _self.percentCert = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          },
          success: async function(res) {
            let temp = await uniCloud.getTempFileURL({
              fileList: res.tempFiles.map((item) => item.url)
            });
            _self.formData.certificate_image = temp.fileList[0].tempFileURL;
            uni.showToast({ icon: 'none', title: '上传成功', duration: 1500 });
          },
          fail: function(err) {
            uni.showToast({ icon: 'none', title: '上传失败', duration: 1500 });
          }
        });
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("user_id,name,avator_image,phone,email,title,direction,description,level,certificate_image,apply_date,audit_status,reject_reason,audit_time,auditor_id,honors,portfolio").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            for (let key in this.formOptions) {
              let pickerIndex = key.lastIndexOf("_index")
              if (pickerIndex > -1) {
                let fieldName = key.substring(0, pickerIndex)
                let fieldData = this.formOptions[fieldName + "_data"];
                if (data[fieldName] && fieldData && fieldData.indexOf(data[fieldName]) > -1) {
                  this.formOptions[fieldName + "_index"] = fieldData.indexOf(data[fieldName])
                }
              }
            }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
